package com.century.sjt.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.century.sjt.R;
//import com.century.sjt.activity.BusinessQualificationActivity;
//import com.century.sjt.activity.CommodityListActivity;
//import com.century.sjt.activity.Topic.HomepageActivity;
//import com.century.sjt.activity.WebViewActivity;
import com.century.sjt.activity.Pay.BusinessQualificationActivity;
import com.century.sjt.activity.Pay.CommodityListActivity;
import com.century.sjt.activity.Topic.HomepageActivity;
import com.century.sjt.entity.Merchant;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.window.ChooseMobilePopupWindow;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * tab 商家信息
 */
public class MerchantItemInfoFragment extends BaseFragment {

    private RequestQueue mQueue;
    private TextView tvMerchantName;
    private TextView etAddress;
    private TextView etTelephone;
    private String telephone;
    private Merchant aMerchant;
    private LinearLayout llCallPhone, LayoutMerchanData;
    private LinearLayout layoutHomepage;
    private LinearLayout layoutCommodity;
    private LinearLayout layout_Level;
    private String payType;

    private ImageView goodsImage[] = new ImageView[4];
    private ImageView shopImage[] = new ImageView[4];
    private ChooseMobilePopupWindow popupWindow;

    private ImageView img1,img2,img3,img4,img5;
    private List<ImageView> imgList = new ArrayList<>();

    private TextView icon_store,icon_position,icon_phone,icon_data;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.sjt_merchant_data_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //读取id
        mQueue = Volley.newRequestQueue(getActivity());
        Intent intent = getActivity().getIntent();
        payType = intent.getStringExtra("payType");
        if (payType.equals("0")) {
            String shopId = intent.getStringExtra("shopId");
//            Bundle data = getArguments();//获得从activity中传递过来的值
            aMerchant = (Merchant) intent.getSerializableExtra("Merchant");
//            shopDetail(shopId);
        } else {
            aMerchant = (Merchant) intent.getSerializableExtra("Merchant");
        }
//        aMerchant=(Merchant)intent.getSerializableExtra("Merchant");

//        String merchantId = intent.getStringExtra("merchantId");
        String balance = intent.getStringExtra("balance");
        initViews();
        if (aMerchant != null) {
            tvMerchantName.setText(aMerchant.getShopName());
            etAddress.setText(aMerchant.getAddress());
//            telephone = aMerchant.getMtext();
            telephone = aMerchant.getTelephone() + " , " + aMerchant.getTelephoneOne();
            etTelephone.setText(telephone);
        }


//        getStoreDetail(aMerchant.getShopId());

        int level = aMerchant.getLevel();
        if (level>5){
            for (int i=0;i<5;i++){
                imgList.get(i).setVisibility(View.VISIBLE);
                imgList.get(i).setImageDrawable(getResources().getDrawable(R.mipmap.diamondorange2x));
                //闪烁
                AlphaAnimation alphaAnimation1 = new AlphaAnimation(0.1f, 1.0f);
                alphaAnimation1.setDuration(1000);
                alphaAnimation1.setRepeatCount(Animation.INFINITE);
                alphaAnimation1.setRepeatMode(Animation.REVERSE);
                imgList.get(i).setAnimation(alphaAnimation1);
                alphaAnimation1.start();
            }
        }else {
            for (int i=0;i<level;i++){
                imgList.get(i).setVisibility(View.VISIBLE);
                imgList.get(i).setImageDrawable(getResources().getDrawable(R.mipmap.diamondorange2x));
            }
        }
    }


    private void initViews() {
        tvMerchantName = (TextView) getView().findViewById(R.id.et_merchantname);
        etAddress = (TextView) getView().findViewById(R.id.et_address);
        etTelephone = (TextView) getView().findViewById(R.id.et_telephone);
        llCallPhone = (LinearLayout) getView().findViewById(R.id.ll_call_phone);
        layout_Level = (LinearLayout) getView().findViewById(R.id.layout_Level);

        img1 = (ImageView) getView().findViewById(R.id.img_1);
        img2 = (ImageView) getView().findViewById(R.id.img_2);
        img3 = (ImageView) getView().findViewById(R.id.img_3);
        img4 = (ImageView) getView().findViewById(R.id.img_4);
        img5 = (ImageView) getView().findViewById(R.id.img_5);

        imgList.add(img1);
        imgList.add(img2);
        imgList.add(img3);
        imgList.add(img4);
        imgList.add(img5);

        shopImage[0] = (ImageView) getView().findViewById(R.id.shopdata_img1);
        shopImage[1] = (ImageView) getView().findViewById(R.id.shopdata_img2);
        shopImage[2] = (ImageView) getView().findViewById(R.id.shopdata_img3);
        shopImage[3] = (ImageView) getView().findViewById(R.id.shopdata_img4);

        goodsImage[0] = (ImageView) getView().findViewById(R.id.iv_goods1);
        goodsImage[1] = (ImageView) getView().findViewById(R.id.iv_goods2);
        goodsImage[2] = (ImageView) getView().findViewById(R.id.iv_goods3);
        goodsImage[3] = (ImageView) getView().findViewById(R.id.iv_goods4);
        LayoutMerchanData = (LinearLayout) getView().findViewById(R.id.ll_gs_zz);
        layoutHomepage = (LinearLayout) getView().findViewById(R.id.layout_homepage);
        layoutCommodity = (LinearLayout) getView().findViewById(R.id.layout_commodity);

        icon_store = (TextView) getView().findViewById(R.id.icon_store);
        icon_position = (TextView) getView().findViewById(R.id.icon_position);
        icon_phone = (TextView) getView().findViewById(R.id.icon_phone);
        icon_data = (TextView) getView().findViewById(R.id.icon_data);

        Typeface iconfont = Typeface.createFromAsset(getActivity().getAssets(), "iconfont.ttf");
        icon_position.setTypeface(iconfont);
        icon_phone.setTypeface(iconfont);
        icon_store.setTypeface(iconfont);
        icon_data.setTypeface(iconfont);
        LayoutMerchanData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), BusinessQualificationActivity.class);
                Bundle mBundle = new Bundle();
                mBundle.putSerializable("Merchant", aMerchant);
                intent.putExtras(mBundle);
                startActivity(intent);
            }
        });
        //跳转到主页
        layoutHomepage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), HomepageActivity.class);
                intent.putExtra("userId", aMerchant.getUserId());
                startActivity(intent);
            }
        });
        layoutCommodity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), CommodityListActivity.class);
                intent.putExtra("shopId",aMerchant.getShopId());
                startActivity(intent);
            }
        });
        llCallPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initMobile();
            }
        });

        layout_Level.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent=new Intent();
//                intent.setClass(getActivity(),WebViewActivity.class);
//                intent.putExtra("title",getActivity().getResources().getString(R.string.tab_level_explain));
//                intent.putExtra("url", Constant.LEVEL_EXPLAIN);
//                startActivity(intent);
            }
        });
//        getGoods(aMerchant.getShopId().toString());//获取商品图片三张
        setLastTopicImage(aMerchant.getLastTopic());//获取话题图片四张
        setNewGoodsImage(aMerchant.getNewGoods());//获取商品图片四张
    }

    /**
     * 获取话题图片四张
     *
     * @param lastTopic
     */
    private void setLastTopicImage(String lastTopic) {
        String[] imageUrls = lastTopic.split("\\|");
        for (int i = 0; i < imageUrls.length; i++) {
            String imageUrl = lastTopic.split("\\|")[i];
            if(!"".equals(imageUrl)) {//如果不为空字符
                if(i<3) {//小于四张图片
                    shopImage[i].setVisibility(View.VISIBLE);
                    Glide.with(getActivity()).load(Constant.BaseImageUrl + imageUrl).into(shopImage[i]);
                }
            }
        }
    }

    /**
     * 获取商品图片四张
     *
     * @param newGoods
     */
    private void setNewGoodsImage(String newGoods) {
        String[] imageUrls = newGoods.split("\\|");
        for (int i = 0; i < imageUrls.length; i++) {
            String imageUrl = newGoods.split("\\|")[i];
            if(!"".equals(imageUrl)) {//如果不为空字符
                if(i<3) {//小于四张图片
                    goodsImage[i].setVisibility(View.VISIBLE);
//                    Log.e("img",imageUrl);
                    Glide.with(getActivity()).load(imageUrl).into(goodsImage[i]);
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void shopDetail(final String shopId) {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), getActivity());
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.ShopDetail, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONObject aData = res.getJSONObject("data");
                        Merchant merchant = new Merchant();
                        merchant.setShopId(aData.getString("shopId"));
                        merchant.setShopName(aData.getString("shopName"));
//                            Log.e("name",aData.getString("shopName"));
                        merchant.setLogo(aData.getString("logo"));
                        merchant.setDiscount(aData.getString("discount"));
                        merchant.setAddress(aData.getString("address"));
                        merchant.setTelephone(aData.getString("telephone"));
                        merchant.setTelephoneOne(aData.getString("telephoneOne"));
                        merchant.setMobile(aData.getString("mobile"));
                        merchant.setDesc(aData.getString("desc"));
                        merchant.setCity(aData.getString("city"));
                        merchant.setImage(aData.getString("image"));
                        aMerchant = merchant;
                        tvMerchantName.setText(aMerchant.getShopName());
                        etAddress.setText(aMerchant.getAddress());
                        telephone = aMerchant.getMobile();
                        etTelephone.setText(telephone);

                    } else {//失败
                        TipUtil.showToast(message, getActivity(), 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), getActivity(), 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
                map.put("shopId", shopId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }


    private void initMobile() {
        popupWindow = new ChooseMobilePopupWindow(getActivity(),aMerchant.getTelephone(),aMerchant.getTelephoneOne());
        popupWindow.showAtLocation(getActivity().findViewById(R.id.paymacth), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
    }


}
